<?php


namespace app\api\controller\batchpay;

use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Log;
use think\Request;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $batchpayStatus = [
        10000 =>   '代付订单创建成功',
        10001 =>   '订单号已存在',
        10002 =>   '账户余额不足',
        10003 =>   '代付金额输入有误'
    ];

    public function index()
    {
        $params = $this->request->post();

        //平台
        $platform = Db('platformLists')->where(['enname' => $params['platform']])->find();
        if (!$platform){
            $this->error('平台不存在');
        }

        // 检测IP
//        $ret = check_ip_allowed_platform(Request::instance()->ip(), $platform['ip']);
//        if (!$ret){
//            $this->error('没有访问权限');
//        }

        // 必要字段验证
        $required = ['title', 'createtime', 'ordersn', 'payplatform', 'money', 'bankname', 'bankcard', 'realname'];
        foreach ($required as $field) {
            if (empty($params[$field])) {
                $this->error(__('Field %s is required', $field));
            }
        }

        //字符转化
        $params['createtime'] = $params['createtime'] ? (int)$params['createtime']: 0;
        $params['ordersn'] = $params['ordersn'] ?? 0;
        // 字段类型转换
        $params['money'] = (float)$params['money'];
        $params['status'] = isset($params['status']) ? (int)$params['status'] : 0;
        $params['ispublic'] = $params['ispublic'] ?? 0;
        if ($params['ispublic'] == 1 && $params['bankopen'] == ''){
            $this->error('对公代付联行号必填');
        }

        //检测重复订单号 表为batchpayLists
        $existOrder = Db::name('batchpayLists')->where(['ordersn' => $params['ordersn']])->find();
        if ($existOrder) {
            $this->success(['code' => 10001,'msg' => $this->batchpayStatus[10001]]);
        }


        //检测账户余额是否足够  账户余额为统计order_lists里所有的订单 减去platform里的修正金额correctmoney  再减去batchpayLists里对应平台status为1的订单统计总和
        $orderTotal = Db::name('order_lists')->where(['platform'=>$params['platform'], 'paystatus' => 1, 'refundstatus' => 0 ])->sum('price');
        $paidTotal = Db::name('batchpayLists')
            ->where(['platform' => $params['platform'], 'status' => 1])
            ->sum('money');
        $availableBalance = $orderTotal - $platform['correctmoney'] - $paidTotal;
        if ($params['money'] > $availableBalance) {
            $this->success(['code' => 10002,'msg' => $this->batchpayStatus[10002]]);
        }

        //检查金额是否正确 不能为负数
        if ($params['money'] <= 0) {
            $this->success(['code' => 10003,'msg' => $this->batchpayStatus[10003]]);
        }

        //有对应平台检测费率 对公对私扣款
        if ($params['ispublic'] == 0) {
            $interval = $platform['publicInterval'];
            $fee = $platform['privateFee'];
        }else{
            $interval = $platform['privateInterval'];
            $fee = $platform['publicFee'];
        }
        $interval = $interval??5000;
        $fee = $fee??5;

        $realFee = ceil($params['money'] / $interval) * $fee;

        $sign = $params['sign'];
        unset($params['sign']);
        unset($params['status']);

        //验签
        $sign2 = urlencode($this->hmacRequest($params,$platform['key']));

        if ($sign2 != $sign){
            $this->error('验签失败，请检查请求参数');
        }

        //检查实际金额是否满足要求  验签完毕  计算实际金额
        $params['fee'] = $realFee;
        $params['realmoney'] = $params['money'] - $params['fee'];
//        $params['ratio'] = $platform['batchpayratio'];
        $params['platform_lists_id'] = $platform['id'];
        $params['platform_name'] = $platform['name'];

        $id = 0;
        try {
            Db::startTrans();
            $params['status'] = 0;
            Db::name('batchpayLists')->insert($params);
            $id = Db::name('batchpayLists')->getLastInsID();

            Db::commit();

        } catch (\Exception $e) {
            $this->error('创建失败: ' . $e->getMessage());
        }

        if ($id == 0){
            $this->error('创建失败');
        }

        $this->success(['code' => 10000,'msg' => $this->batchpayStatus[10000]]);
    }

    protected function hmacRequest($params, $key, $encryptType = "1")
    {
        if ("1" == $encryptType) {
            return md5(implode("", $params) . $key);
        } else {
            $private_key = openssl_pkey_get_private($key);
            $params = implode("", $params);
            openssl_sign($params, $sign, $private_key, OPENSSL_ALGO_MD5);
            openssl_free_key($private_key);
            $sign = base64_encode($sign);
            return $sign;
        }
    }

    private function checkIpInRanges($ip, $ranges)
    {
        foreach ($ranges as $range) {
            if ($this->ipInRange($ip, $range)) {
                return true;
            }
        }
        return false;
    }

    private function ipInRange($ip, $range)
    {
        if (strpos($range, '/') !== false) {
            // CIDR处理
            list($subnet, $mask) = explode('/', $range);
            $ipLong = ip2long($ip);
            $subnetLong = ip2long($subnet);
            $maskLong = ~((1 << (32 - $mask)) - 1);
            return ($ipLong & $maskLong) === ($subnetLong & $maskLong);
        }
        return $ip === $range;
    }


}
